<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Camera (Mobile)</title>
    <style>
        #localVideo {
            background-color: #CF3;
            width: 320px;
            height: 240px;
            margin: 10px;
        }
        #remoteVideo {
            background-color: #9CF;
            width: 320px;
            height: 240px;
            margin: 10px;
        }
        .video-container {
            display: flex;
            flex-wrap: wrap;
        }
    </style>
</head>
<body>
    <div class="video-container">
        <video id="localVideo" autoplay playsinline muted></video>
        <video id="remoteVideo" autoplay playsinline></video>
    </div>

    <script>
        const localVideo = document.getElementById('localVideo');
        const remoteVideo = document.getElementById('remoteVideo');

        let localStream;
        let peerConnection;
        const ws = new WebSocket('wss://192.168.0.120:8888');

        // 初始化 RTCPeerConnection
        function createPeerConnection() {
            peerConnection = new RTCPeerConnection({
                iceServers: [{ urls: 'stun:stun.l.google.com:19302' }]
            });

            // 处理远程视频流
            peerConnection.ontrack = (event) => {
                console.log('Received track:', event.track);
                if (event.track.kind === 'video') {
                    remoteVideo.srcObject = event.streams[0];
                }
            };

            // 处理 ICE Candidate
            peerConnection.onicecandidate = (event) => {
                if (event.candidate) {
                    ws.send(JSON.stringify({ 
                        type: 'candidate', 
                        candidate: event.candidate 
                    }));
                }
            };
            
            // 添加本地视频流到连接中
            if (localStream) {
                localStream.getTracks().forEach(track => {
                    peerConnection.addTrack(track, localStream);
                });
            }
        }

        // WebSocket 消息处理
        ws.onmessage = async (message) => {
            const data = JSON.parse(message.data);
            console.log('Received data:', data);

            if (data.type === 'offer') {
                if (!peerConnection) {
                    await startCamera();
                }
                await peerConnection.setRemoteDescription(
                    new RTCSessionDescription(data.offer)
                );
                const answer = await peerConnection.createAnswer();
                await peerConnection.setLocalDescription(answer);
                ws.send(JSON.stringify({ type: 'answer', answer: answer }));
				console.log('Mobile send answer');
            } else if (data.type === 'candidate') {
                if (peerConnection) {
                    try {
                        await peerConnection.addIceCandidate(
                            new RTCIceCandidate(data.candidate)
                        );
                    } catch (e) {
                        console.error('Error adding ICE candidate:', e);
                    }
                }
            }
        };

        // 启动摄像头
        async function startCamera() {
            try {
                const constraints = {
                    video: { facingMode: "user" }, // 使用前置摄像头
                    audio: false
                };
                localStream = await navigator.mediaDevices.getUserMedia(constraints);
                localVideo.srcObject = localStream;
                
                createPeerConnection();
            } catch (error) {
                console.error('Error accessing camera:', error);
            }
        }

        // 当WebSocket连接成功后启动摄像头
        ws.onopen = () => {
            console.log('WebSocket connected');
            startCamera();
        };

        ws.onerror = (error) => {
            console.error('WebSocket error:', error);
        };
    </script>
</body>
</html>